checkLogin(true);
$(function () {
    $.post("../php/categories/getCategoriesAll.php", function (res) {
        if (res.code == 100) {
            var html = $("#mt").tmpl(res.data);
            $("#dataset").append(html);
        }
    }, "json");


    $("#dataset").on("click", ".del", function () {
        var id = $(this).parent().parent().attr("category_id");
        layer.confirm("您是否要删除该分类", {icon: 3}, function (index) {
            if (index) {
                $.post("../php/categories/deleteCategory.php", {id: id}, function (res) {
                    if (res.code == 100) {
                        layer.alert(res.msg, {icon: 1}, function (index) {
                            location.reload();
                        });
                    }
                    else {
                        layer.alert(res.msg, {icon: 2}, function (index) {
                            location.reload();
                        });
                    }
                }, "json");
            }
        })
    })

    var category_id = "";
    $("#dataset").on("click", ".edit", function () {
        category_id = $(this).parent().parent().attr("category_id");
        $.post("../php/categories/getCategoryById.php", {id: category_id}, function (res) {
            if (res.code == 100) {
                $("#name").val(res.data.name);
                $("#slug").val(res.data.slug);
                $("#btn-suer").text("编辑");
            }
        }, "json");
    })

    $("#btn-suer").on("click", function () {
        var data = $("#cat-data").serialize();
        if (category_id == "") {
            $.post("../php/categories/addCategory.php", data, function (res) {
                if (res.code == 100) {
                    layer.alert(res.msg, {icon: 1}, function (index) {
                        location.reload();
                    });
                }
            }, "json");
        } else {
            data += "&id=" + category_id;
            $.post("../php/categories/updateCategoryById.php", data, function (res) {
                if (res.code == 100) {
                    layer.alert(res.msg, {icon: 1}, function (index) {
                        location.reload();
                    });
                }
            }, "json");
        }
        return false;
    });
});